const db = require('../db/index')
const axios = require('axios')
const EVALUATE_SERVICE_URL = 'http://api.hzc319820.cn:1949';
// 创建面试管理接口
const postInterview = async (req, res) => {
  console.log(req.body);
  const { user_id, position, company_id } = req.body

  if (!user_id || !position || !company_id) {
    console.log(req.body);
    return res.cc({
      code: 400,
      message: '参数错误'
    })
  }
  const sql = 'insert into InterviewSessions set ?'
  await db.query(sql, { user_id, position, company_id, start_time: new Date() })
  return res.send({
    code: 200,
    message: '创建成功！',
    data: {
      session_id: result[0].insertId // 返回新记录的ID
    }
  })
}

//面试开始接口
const startInterview = async (req, res) => {
  const { session_id, company_id } = req.body;

  // 1. 校验session_id和company_id是否匹配
  const [sessionRows] = await db.query(
    'SELECT * FROM InterviewSessions WHERE id = ? AND company_id = ?',
    [session_id, company_id]
  );
  if (!sessionRows || sessionRows.length === 0) {
    return res.cc({ code: 400, message: '面试会话不存在或company_id不匹配' });
  }

  // 1. 查询公司信息（适配新字段）
  const [companyRows] = await db.query(
    'SELECT company_name, position, content_text FROM CompanyDocuments WHERE id = ?',
    [company_id]
  );
  if (companyRows.length === 0) {
    return res.cc({ code: 400, message: '公司信息不存在' });
  }
  const { company_name, position, content_text } = companyRows[0];

  // 2. 组装新AI接口参数
  const requestData = {
    company_info: { company: company_name, position },
    resume_info: { resume_text: content_text }
  };

  // 3. 调用新AI服务接口
  let question = '';
  try {
    const aiRes = await axios.post('http://api.hzc319820.cn:1949/interview/generate', requestData);
    question = aiRes.data.answer;
  } catch (e) {
    console.error('AI服务调用失败:', e);
    return res.cc({ code: 500, message: 'AI服务调用失败' });
  }

  // 4. 存入InterviewQuestions表
  let resultQuestions = [];
  try {
    const [insertResult] = await db.query(
      'INSERT INTO InterviewQuestions (session_id, question_text) VALUES (?, ?)',
      [session_id, question]
    );
    resultQuestions.push({ id: insertResult.insertId, question_text: question });
  } catch (e) {
    console.error('数据库插入失败:', e);
    return res.cc({ code: 500, message: '数据库插入失败' });
  }

  res.send({
    code: 200,
    message: '面试问题生成成功',
    data: resultQuestions
  });
};

// {
//   "session_id": "123",
//   "question_text": ["问题1", "问题2", "问题3"],
//   "created_at": "2024-01-01"
// }  面试问题格式
// 用户向ai获取面试问题接口
const getQuestion = async (req, res) => {
  // console.log(req.body);
  const { session_id, question_text, created_at } = req.body
  if (!session_id || !question_text || !created_at) {
    console.log(req.body);
    return res.cc({
      code: 400,
      message: '参数错误'
    })
  }

  // 转数组
  questions = JSON.parse(question_text);
  for (let text of questions) {
    console.log('shuju', text);
    const sql = `insert into InterviewQuestions set ?`
    await db.query(sql, { session_id, question_text: text, created_at })
  }
  return res.send({
    code: 200,
    message: '添加问题成功'
  })
}

// 用户回答接口
const answer = async (req, res) => {
  const { question_id, answer_text, answer_time, session_id } = req.body;

  if (!question_id || !answer_time || !answer_text || !session_id) {
    console.log(req.body);
    return res.cc({
      code: 400,
      message: '参数错误'
    });
  }

  try {
    const sql = 'insert into UserAnswers set ?';
    await db.query(sql, { question_id, answer_text, answer_time, session_id });

    return res.send({
      code: 200,
      message: '获取用户回答成功！',
    });
  } catch (err) {
    console.error('Database error:', err);
    return res.cc({
      code: 500,
      message: '服务器错误'
    });
  }
}

// 获取自己面试的问题接口(面试复盘)
const getMyQuestion = async (req, res) => {
  console.log(req.query);

  const { session_id } = req.query;
  console.log("session_id:", session_id, typeof session_id);

  const sql = 'SELECT * FROM InterviewQuestions WHERE session_id = ?';
  try {
    const [rows, fields] = await db.query(sql, [session_id]);
    console.log("Query rows:", rows);
    console.log("Query fields:", fields);

    if (!rows || rows.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '该面试会话不存在或没有相关问题',
      });
    }

    return res.send({
      code: 200,
      message: '获取面试问题成功！',
      data: rows
    });
  } catch (error) {
    console.error("Database query error:", error);
    return res.status(500).json({
      code: 500,
      message: '服务器错误',
    });
  }
};

// 获取自己面试答案接口
const getMyAnswer = async (req, res) => {
  console.log(req.query);
  const session_id = req.query.session_id
  const sql = 'select * from  UserAnswers where session_id=?'
  const results = await db.query(sql, session_id)
  return res.send({
    code: 200,
    message: '获取面试答案成功！',
    data: results
  })
}

// 追问接口：生成后续面试问题
const followupQuestion = async (req, res) => {
  const { session_id, company_id } = req.body;

  // 1. 查公司信息
  const [companyRows] = await db.query(
    'SELECT company_name, position, content_text FROM CompanyDocuments WHERE id = ?',
    [company_id]
  );
  if (!companyRows || companyRows.length === 0) {
    return res.cc({ code: 400, message: '公司信息不存在' });
  }
  const { company_name, position, content_text } = companyRows[0];

  // 2. 查历史问答
  const [questions] = await db.query(
    'SELECT id, question_text FROM InterviewQuestions WHERE session_id = ? ORDER BY id ASC',
    [session_id]
  );
  const [answers] = await db.query(
    'SELECT question_id, answer_text FROM UserAnswers WHERE session_id = ?',
    [session_id]
  );
  const previous_qa = questions.map(q => {
    const answerObj = answers.find(a => a.question_id === q.id);
    return {
      question: q.question_text,
      answer: answerObj ? answerObj.answer_text : ''
    };
  });

  // 3. 组装请求参数
  const requestData = {
    company_info: { company: company_name, position },
    resume_info: { resume_text: content_text },
    previous_qa
  };

  // 4. 调用AI followup接口
  let followup = '';
  try {
    const aiRes = await axios.post('http://api.hzc319820.cn:1949/interview/followup', requestData);
    followup = aiRes.data.answer;
  } catch (e) {
    console.error('AI服务调用失败:', e);
    return res.cc({ code: 500, message: 'AI服务调用失败' });
  }

  // 5. 存入InterviewQuestions表
  let result = null;
  try {
    const [insertResult] = await db.query(
      'INSERT INTO InterviewQuestions (session_id, question_text) VALUES (?, ?)',
      [session_id, followup]
    );
    result = { id: insertResult.insertId, question_text: followup };
  } catch (e) {
    console.error('数据库插入失败:', e);
    return res.cc({ code: 500, message: '数据库插入失败' });
  }

  res.send({
    code: 200,
    message: '追问生成成功',
    data: result
  });
};

//评估分数
const getScore = async (req, res) => {
  try {
    const { qa_pairs, session_id } = req.body;

    // 1. 参数验证
    if (!qa_pairs || !Array.isArray(qa_pairs) || qa_pairs.length === 0) {
      return res.status(400).json({
        code: 400,
        message: '缺少有效的qa_pairs参数',
        details: 'qa_pairs应为非空数组，每个元素应包含question和answer字段'
      });
    }

    // 验证session_id是否存在
    if (!session_id) {
      return res.status(400).json({
        code: 400,
        message: '缺少session_id参数',
        details: '需要提供会话ID用于关联评估记录'
      });
    }

    // 验证每个qa_pair的结构
    for (const pair of qa_pairs) {
      if (!pair.question || !pair.answer) {
        return res.status(400).json({
          code: 400,
          message: '无效的qa_pair结构',
          details: '每个qa_pair必须包含question和answer字段'
        });
      }
    }

    // 2. 调用评估服务
    const response = await axios.post(EVALUATE_SERVICE_URL + '/evaluate/batch', {
      qa_pairs: qa_pairs
    }, {
      headers: { 'Content-Type': 'application/json' },
      timeout: 360000
    });

    // 3. 处理评估结果并创建或更新数据库记录（原生SQL实现）
    if (response.data) {
      // 提取评估结果的关键字段
      const { advantages, disadvantages, suggestions, score, answer } = response.data;

      // 查找是否已有评估记录
      const [rows] = await db.query('SELECT * FROM Evaluations WHERE session_id = ?', [session_id]);
      if (rows && rows.length > 0) {
        // 已有则更新
        await db.query(
          'UPDATE Evaluations SET good = ?, bad = ?, suggest = ?, score = ?, feedback = ?, evaluation_time = ? WHERE session_id = ?',
          [advantages, disadvantages, suggestions, score, answer, new Date(), session_id]
        );
      } else {
        // 没有则新建
        await db.query(
          'INSERT INTO Evaluations (session_id, good, bad, suggest, score, feedback, evaluation_time) VALUES (?, ?, ?, ?, ?, ?, ?)',
          [session_id, advantages, disadvantages, suggestions, score, answer, new Date()]
        );
      }

      return res.json({
        code: 200,
        message: '评估成功且结果已存储',
        data: {
          ...response.data,
        }
      });
    } else {
      throw new Error('评估服务返回格式异常');
    }

  } catch (error) {
    console.error('评估失败:', error);

    // 错误处理
    if (error.response) {
      return res.status(error.response.status).json({
        code: error.response.status,
        message: `评估服务错误: ${error.response.data.message || '未知错误'}`,
        details: error.response.data
      });
    } else if (error.request) {
      return res.status(503).json({
        code: 503,
        message: '评估服务无响应',
        details: '请检查评估服务是否正常运行或网络连接是否正常'
      });
    } else if (error.code === 'ECONNABORTED') {
      return res.status(504).json({
        code: 504,
        message: '评估服务请求超时'
      });
    } else {
      return res.status(500).json({
        code: 500,
        message: `评估失败: ${error.message}`,
        details: error.stack
      });
    }
  }
};

module.exports = {
  postInterview,
  getQuestion,
  answer,
  getMyQuestion,
  getMyAnswer,
  startInterview,
  followupQuestion,
  getScore,
}